# Copyright (C) 2007 "dbsolution sas" 
#
# This file is part of Weebotee.
#
# Weebotee is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# Weebotee is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with Weebotee.  If not, see <http://www.gnu.org/licenses/>.

from django import newforms as forms
from django.contrib.auth.models import User, Group
from apps.core.models.section import Section
from apps.core.backend.views.forms.base_form import BaseForm
from libs.plug_core import *


shorty = lambda n,l: (n.__len__()>l) and n[:l]+"..." or n

class SectionForm(BaseForm):  
    # SECTION DATA
    name = forms.CharField(label="Nome Sezione")
    description = forms.CharField(label='Descrizione', required=False)
    viewtype = forms.ChoiceField(label='Tipo')
    order = forms.ChoiceField(label="Ordinamento", required=False)
    # DIPENDENZE
    parent = forms.ChoiceField(label="Figlia di", required=False)
    # SEO METADATA
    slug = forms.CharField(label='Slug', required=False)
    pagetitle = forms.CharField(label='Titolo pagina', required=False)
    keywords = forms.CharField(label='Keywords', required=False)
    metatags = forms.CharField(label='Metatags', required=False)
    
    def __init__(self, *args, **kwargs):
        self.sid = None
        self.PARENT_CHOICES = [('', '------')]+[(s.id, shorty(s.name,10)) for s in Section.objects.all()]
        list_of_views = scan_applications('get_views')
        self.VIEW_CHOICES = build_sections_list(list_of_views) 
        self.ORDER_CHOICES = [(o.id, "%d: %s" %(o.order, o.name)) for o in Section.objects.all()]
        self.base_fields['description'].widget = forms.widgets.Textarea()
        self.base_fields['metatags'].widget = forms.widgets.Textarea()
        self.base_fields['parent'].choices = self.PARENT_CHOICES
        self.base_fields['viewtype'].choices = self.VIEW_CHOICES
        self.base_fields['order'].choices = self.ORDER_CHOICES 
        try:
            self.sid = kwargs['initial']['id']
            sec = Section.objects.get(id=self.sid)
        except:
            sec = None
        super(SectionForm, self).__init__(sec, *args, **kwargs)
    
    def clean_slug(self):
        try: 
            Section.objects.filter(slug=self.cleaned_data['slug'])
        except Exception, e:
            raise forms.ValidationError(u"La stringa Slug specificata e' stata gia' usata")
        return self.cleaned_data['slug']
        
    def save(self, tp='section',  *args, **kwargs):
        try:
            s  = Section.objects.get(id=self.sid)
        except:
            s = Section()
        
        s.name = self.cleaned_data['name']
        s.description= self.cleaned_data['description']
        s.viewtype = self.cleaned_data['viewtype']
        s.order= self.cleaned_data['order']
        
        s.status = self.cleaned_data['status']
        try:
            s.parent = Section.objects.get(pk=self.cleaned_data['parent'])
        except:
            s.parent_id = None
        s.slug = self.cleaned_data['slug']
        s.pagetitle = self.cleaned_data['pagetitle']
        s.keywords = self.cleaned_data['keywords']
        s.metatags = self.cleaned_data['metatags']
        s.stype = tp
        s.owner = User.objects.get(pk=self.cleaned_data['owner'])
        s.owner_alias = self.cleaned_data['owner_alias']
        s.save()
        for g in self.cleaned_data['groupAdd']:
            s.group.add(g)
        for g in self.cleaned_data['groupRmv']:
            s.group.remove(g)
        return
